package com.tanhua.dubbo.api.impl;

import com.tanhua.domain.mongo.UserLocation;
import com.tanhua.domain.vo.UserLocationVo;
import com.tanhua.dubbo.api.UserLocationApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@Service(timeout = 30000)
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveLocation(Double latitude, Double longitude, String addrStr, Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        if(!mongoTemplate.exists(query, UserLocation.class)){
            UserLocation location = new UserLocation();
            location.setUserId(userId);
            location.setCreated(System.currentTimeMillis());
            location.setLocation(new GeoJsonPoint(longitude,latitude));
            location.setAddress(addrStr);
            location.setUpdated(System.currentTimeMillis());
            location.setLastUpdated(System.currentTimeMillis());
            mongoTemplate.save(location);
        }else{
            Update update = new Update();
            update.set("location", new GeoJsonPoint(longitude,latitude));
            update.set("lastUpdated",System.currentTimeMillis());
            update.set("address",addrStr);
            update.set("updated",System.currentTimeMillis());
            mongoTemplate.updateFirst(query,update,UserLocation.class);
        }
    }

    @Override
    public List<UserLocationVo> searchNearBy(Long distance, Long userId) {
        //查询当前用户的地理位置
        Query query = new Query(Criteria.where("userId").is(userId));
        UserLocation location = mongoTemplate.findOne(query, UserLocation.class);

        //获取用户的坐标
        GeoJsonPoint point = location.getLocation();

        //准备参数
        //画圆半径的距离
        Distance d = new Distance(distance / 1000, Metrics.KILOMETERS);

        //根据用户的坐标画图
        Circle circle = new Circle(point, d);

        //根据当前用户的坐标画圆，搜索附近的人
        Query q = new Query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> list = mongoTemplate.find(q, UserLocation.class);
        return UserLocationVo.formatToList(list);
    }
}
